#include "InitOgreApp.h"


InitOgreApp::InitOgreApp(void):m_Root(NULL),m_Window(NULL),m_MainCamera(NULL),m_SceneManager(NULL)
{
}


InitOgreApp::~InitOgreApp(void)
{
	Ogre::WindowEventUtilities::removeWindowEventListener(m_Window, this);
	windowClosed(m_Window);
	delete m_Root;
}

void InitOgreApp::InitApp()
{
	m_Root = new Ogre::Root( "", "" );

	//Load Render System

#ifdef _DEBUG
	m_Root->loadPlugin( "RenderSystem_GL_d" );     // for a debug build
#else
	m_Root->loadPlugin( "RenderSystem_GL" );       // for a release build
#endif

	// Select the Renderer
	bool ok = false;

	Ogre::RenderSystemList render_sys_list = m_Root->getAvailableRenderers();
	Ogre::RenderSystemList::iterator it_rs = render_sys_list.begin() ;
	
	while ( it_rs != render_sys_list.end() )
	{
		Ogre::RenderSystem *render_sys = *(it_rs++);
		if ( render_sys->getName().find( "OpenGL" ) != Ogre::String::npos )
		{
			m_Root->setRenderSystem( render_sys );
			ok = true;
			break;
		}
	}
	if(!ok){throw new OgreException("Loading Render System failed");}

	m_Root->initialise( false );

	//Create Scene Manager
	m_SceneManager = m_Root->createSceneManager(Ogre::ST_GENERIC);
	
	//Virtual functions
	CreateRenderWindow();

	SetCamera();
	SetViewport();
	SetLight();

	SetListener();
}

void InitOgreApp::Render()
{
	m_Root->startRendering();
}

void InitOgreApp::CreateRenderWindow()
{
	//Create Window
	m_Window = m_Root->createRenderWindow("Ogre",1024,720,false);
	//Add Window Event Listener
	Ogre::WindowEventUtilities::addWindowEventListener( m_Window, this );
}

void InitOgreApp::FullScreen()
{
	RECT rc;
	GetWindowRect(GetDesktopWindow(), &rc);
	m_Window->reposition(0,0);
	m_Window->setFullscreen(true,rc.right,rc.bottom);
	
}

void InitOgreApp::SetViewport()
{
	
	//Create one viewport, entire window
	Ogre::Viewport *viewport = m_Window->addViewport(m_MainCamera);
	viewport->setBackgroundColour( Ogre::ColourValue::Black );
	
	//Alter the camera aspect ratio to match the viewport
	if (m_MainCamera != NULL)
	{
		m_MainCamera->setAspectRatio(  Ogre::Real( viewport->getActualWidth() ) /  Ogre::Real( viewport->getActualHeight() ) );
	}
}


void InitOgreApp::SetCamera()
{
	m_MainCamera = m_SceneManager->createCamera("MainCamera");

	m_MainCamera->lookAt(Ogre::Vector3(0,0,-300));
	m_MainCamera->setPosition( 0, 0, 500 );

	m_MainCamera->setNearClipDistance( 1 );
	m_MainCamera->setFarClipDistance( 1000 );
	m_MainCamera->setFOVy( Ogre::Degree( 45 ) );
}


void InitOgreApp::SetLight()
{

}

void InitOgreApp::SetListener()
{
	//Set Frame Listener
	m_Root->addFrameListener(this);

}

void InitOgreApp::windowResized( Ogre::RenderWindow *_rwin )
{
	Ogre::Viewport* viewport = _rwin->getViewport( 0 );
	m_MainCamera->setAspectRatio(  Ogre::Real( viewport->getActualWidth() ) /  Ogre::Real( viewport->getActualHeight() ) );
}



